package com.bx.implatform.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bx.implatform.config.props.WechatProperties;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WeChatUtils {
    @Resource
    private WechatProperties wechatProperties;

    /**
     * 获取微信用户的access_token
     *
     * @param code 微信小程序登录时获取的code
     * @return 包含access_token和openid的Map
     * @throws Exception
     */
    public Map<String, String> getAccessToken(String code) throws Exception {
        OkHttpClient client = new OkHttpClient();
        String url = wechatProperties.getAccessTokenUrl() + "?appid=" + wechatProperties.getAppId() + "&secret=" + wechatProperties.getAppSecret() + "&js_code=" + code
            + "&grant_type=authorization_code";
        Request request = new Request.Builder().url(url).get().build();
        Response response = client.newCall(request).execute();
        String responseStr = response.body().string();
        JSONObject jsonObject = JSON.parseObject(responseStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        String unionid = jsonObject.getString("unionid");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", accessToken);
        map.put("openid", openid);
        map.put("unionid", unionid);
        map.put("session_key", jsonObject.getString("session_key"));
        return map;
    }

    public String getAccessToken() throws Exception {
        String requestUrl = wechatProperties.getSubscribeAccessTokenUrl() + "&appid=" + wechatProperties.getAppId()
                + "&secret=" + wechatProperties.getAppSecret();
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();
        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken = jsonObject.getString("access_token");
        System.out.println(accesstoken);
        return accesstoken;
    }

    /**
     * 小程序消息通知
     * @param openId 接收者（用户）的 openid
     * @param page 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @param map //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
     */
    public void subscribeMessage(String openId, String page,JSONObject map) {
        try {
            String accessToken = getAccessToken();
            JSONObject subscribeMessage = new JSONObject();
            // 拼接数据
            subscribeMessage.put("access_token", accessToken);
            subscribeMessage.put("touser", openId);
            subscribeMessage.put("template_id", wechatProperties.getTemplateId());//事先定义好的模板id
            subscribeMessage.put("page", wechatProperties.getTemplatePage());//点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            subscribeMessage.put("data", map);
            String json = JSONObject.toJSONString(subscribeMessage);
            JsonNode ret = null;
            ret = Unirest.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken)
                    .body(json).asJson().getBody();
            System.out.println(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        WeChatUtils weChatUtils = new WeChatUtils();
//        JSONObject map = new JSONObject();
////        map.put("date4", new TemplateData(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())));
////        map.put("thing12", new TemplateData("温度过高"));
////        map.put("thing1", new TemplateData("氙灯老化试验箱"));
////        map.put("thing2", new TemplateData("BJYSL-SN-500"));
////        map.put("thing3", new TemplateData("实验箱温度"));
//        map.put("time4.DATA", new JSONObject().fluentPut("value",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())));
//        map.put("thing6.DATA", new JSONObject().fluentPut("value","测试"));
//        map.put("thing2.DATA", new JSONObject().fluentPut("value","测试消息"));
//        map.put("thing5.DATA", new JSONObject().fluentPut("value","点击回复TA"));
//        weChatUtils.subscribeMessage("oPUD35dzUstVi8VDqMQOW1P6EElY", "", map);
//    }

}

